package com.csxh.web.userinfo.servlet;

import java.io.IOException;
import java.util.regex.Matcher;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.csxh.web.userinfo.bean.Pager;
import com.csxh.web.userinfo.bean.User;
import com.csxh.web.userinfo.service.UserService;
import com.csxh.web.userinfo.util.StringUtil;
import com.csxh.web.userinfo.util.WebUtil;

/**
 * Servlet implementation class IndexServlet
 */
@WebServlet("/index.servlet")
public class IndexServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public IndexServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		//判断用户是否已经登录
		boolean b=WebUtil.checkLoginUser(request);
		if (!b) {
			//System.out.println("还没有登录");
			//没有登录，此时要转发到登录页面
			//System.out.println("没有登录");//iso-8859-1
			response.setCharacterEncoding("utf-8");
			request.getRequestDispatcher("WEB-INF/jsp/login.jsp").forward(request, response);
		}else{
			
			User loginUser=WebUtil.getLoginUser(request);
			
			UserService service=new UserService();
			Integer pageSize=WebUtil.intParam(request,WebUtil.PAGE_SIZE,3);
			Integer pageIndex=WebUtil.intParam(request,WebUtil.PAGE_INDEX,1);
			Pager<User> pager=new Pager<User>();
			
			String queryField,queryParam,whereClase;
			queryField="all";
			queryParam="";
			String op=WebUtil.strParam(request, WebUtil.OP, WebUtil.OP_QUERY);
			
			if(op.equals(WebUtil.OP_QUERY)){				
				
				//通过传来的cookie获取查询字段与查询参数
				queryField=WebUtil.strCookie(request, WebUtil.QUERY_FIELD, "all");	
				queryParam=WebUtil.strCookie(request, WebUtil.QUERY_PARAM, "");	
			   
				if(queryField.equals("name")){
					
					whereClase= "`name` like %?% and `id`<>? ";
					pager=service.findUserPager(pageSize, pageIndex,whereClase,queryParam,loginUser.getId());
					
				}else if(queryField.equals("age")){
					
					String regex="(\\d+)\\s*-\\s*(\\d+)";
					Matcher m=StringUtil.findMatcher(queryParam,regex);
					if(m.find()){

						
						Integer min=Integer.parseInt(m.group(1));
						Integer max=Integer.parseInt(m.group(2));
						//构建查询条件
						whereClase= " (`age` between ? and ?) and `id`<>? ";
						
						pager=service.findUserPager(pageSize, pageIndex,whereClase,min,max,loginUser.getId());
						
						
						
					}
				}else{
					
					pager=service.findUserPager(pageSize, pageIndex,"`id`<>?",loginUser.getId());
					
				}
				
			}else if(op.equals(WebUtil.OP_ADD)){
				
				//提取用户对象的参数
				String name=request.getParameter("name");
				String password=request.getParameter("password");
				String sex=request.getParameter("sex");
				Integer age=WebUtil.intParam(request, "age", 0);
				String phone=request.getParameter("phone");
				String email=request.getParameter("email");
				String address=request.getParameter("address");
				//创建用户对象
				User u=new User();
				u.setId(null);//自动递增字段要设为空
				u.setName(name);
				u.setPassword(password);
				u.setSex(sex);
				u.setAge(age);
				u.setPhone(phone);
				u.setEmail(email);
				u.setAddress(address);
				//插入到数据库
				b=service.insertUser(u);
				
				if(b){
					//查询最后一页的数据
					pager=service.findUserLastPager(pageSize,"`id`<>?",loginUser.getId());
					//将分页片断html包含进来，传给浏览器处理
					//查询分页记录，不考虑cookie中保存的分页条件
					pager.setShowJsp("index.jsp");
					//将用户列表保存到请求级别上下文中，以便在jsp页面中通过EL表达式取出
					request.setAttribute(WebUtil.PAGER, pager);
					//判断指定的派发资源是否存在
					RequestDispatcher rdp=request.getRequestDispatcher("WEB-INF/fragment/pager.jsp");
					if(null!=rdp){
						//将派发的资源经翻译后包含进行
						response.setCharacterEncoding("utf-8");
						rdp.include(request, response);
						//将翻译后的分页html传回浏览器
						
					}
					
				}else{
					response.getWriter().append("");
				}
				return;
				
			}else if(op.equals(WebUtil.OP_DEL)){
				
				//根据id号删除指定的用户
				Integer id=WebUtil.intParam(request, "id", null);
				
				b=service.deleteUser(id);
				if(b){
					//查询分页记录，不考虑cookie中保存的分页条件
					pager=service.findUserPager(pageSize, pageIndex,"`id`<>?",loginUser.getId());
					
					pager.setShowJsp("index.jsp");
					//将用户列表保存到请求级别上下文中，以便在jsp页面中通过EL表达式取出
					request.setAttribute(WebUtil.PAGER, pager);
					//判断指定的派发资源是否存在
					RequestDispatcher rdp=request.getRequestDispatcher("WEB-INF/fragment/pager.jsp");
					if(null!=rdp){
						//将派发的资源经翻译后包含进行
						response.setCharacterEncoding("utf-8");
						rdp.include(request, response);
						//将翻译后的分页html传回浏览器
						
					}	
				}else{
					//没有删除成功
					response.getWriter().append(WebUtil.OP_FAIL);
				}
				
				return;
			}else if(op.equals(WebUtil.OP_UPDATE)){
			
				//获取传过来的参数
				Integer id=WebUtil.intParam(request, "id", -1);
				String name=request.getParameter("name");
				String password=request.getParameter("password");
				String sex=request.getParameter("sex");
				Integer age=WebUtil.intParam(request, "age", 0);
				//创建用户对象
				User u=new User();
				u.setId(id);
				u.setName(name);
				u.setPassword(password);
				u.setSex(sex);
				u.setAge(age);
				//更新数据库
				b=service.updateUser(u);
				if(b){
					//返回成功标记
					response.getWriter().append(WebUtil.OP_OK);
				}else{
					//返回失败标记
					response.getWriter().append(WebUtil.OP_FAIL);
				}
				
				return;
			}
			//System.out.println("已经登录");
			//已经登录,准备用户列表信息，登录用户除外
			//业务功能委托给服务层完成
			pager.setShowJsp("index.jsp");
			//将用户列表保存到请求级别上下文中，以便在jsp页面中通过EL表达式取出
			request.setAttribute(WebUtil.PAGER, pager);
			//System.out.println(pager.getBeanList());
		}
		
	}

}
